#pragma once

#include <cstring>
#include <string>
#include <cstdarg>
#include <sys/types.h>
#include <unistd.h>
#include <ctime>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define DEBUG 0
#define INFO 1
#define WARNING 2
#define ERROR 3
#define FATAL 4

std::string filename = "log.txt";

static std::string toLevelString(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case INFO:
        return "INFO";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return "UNKNOW";
    }
}

static std::string gettime()
{
    time_t curr = time(nullptr);
    struct tm *tmp = localtime(&curr);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d-%d-%d",
             tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour,
             tmp->tm_min, tmp->tm_sec);
    return buffer;
}

void logmessage(int level, const char *fomart, ...)
{
    // va_list p;
    // va_arg(p, int);      // 根据类型提取参数
    // va_start(p, fomart); // p指向可变参数的起始地址
    // va_end(p);           // p置空

    char logleft[1024];
    std::string level_string = toLevelString(level);
    std::string cur_time = gettime();

    snprintf(logleft, sizeof(logleft), "[%s] [%s] [%d] ", level_string.c_str(), cur_time.c_str(), getpid());

    char logright[1024];
    va_list p;
    va_start(p, fomart);
    vsnprintf(logright, sizeof(logright), fomart, p);
    va_end(p);

    //打印
    printf("%s%s\n", logleft, logright);
    // 保存到文件
    // FILE *fp = fopen(filename.c_str(), "a");
    // if(fp == nullptr) return;
    // fprintf(fp,"%s%s",logleft, logright);
    // //fflush(fp);

    // fclose(fp);
}